package middleware.activemq.topic;

import middleware.activemq.queue.QueueProducer;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author ME
 * @date 2017/7/24
 * @description 消息的生产者（发送者）
 */
public class TopicProducer {
    /**默认连接用户名*/
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    /**默认连接密码*/
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    /**默认连接地址*/
    private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
    /**发送的消息数量*/
    private static final int MESSAGE_NUM = 10;

    public static void main(String[] args) {
        // 连接工厂
        ConnectionFactory connectionFactory;
        // 连接
        Connection connection = null;
        // 会话 接受或者发送消息的线程
        Session session = null;
        // 消息的目的地
        Destination destination;
        // 消息生产者
        MessageProducer producer = null;
        // 实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(TopicProducer.USERNAME, TopicProducer.PASSWORD, TopicProducer.BROKER_URL);

        try {
            // 通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            // 启动连接
            connection.start();
            // 创建session
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个名称为 TopicWorld 的消息队列
            destination = session.createTopic("TopicWorld");
            // 创建消息生产者
            producer = session.createProducer(destination);
            // 发送消息
            sendMessage(session, producer);

            session.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            QueueProducer.releaseRes(producer, null, session, connection);
        }

        System.out.println("\n=====生产者发送成功。。");
    }

    /**
     * 发送消息
     * @param session
     * @param messageProducer  消息生产者
     * @throws Exception
     */
    public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception {
        System.out.println("=====生产者开始生产消息。。\n");
        for (int i = 1; i <= TopicProducer.MESSAGE_NUM; i++) {
            // 读取配置文件里的消息
            //Properties prop = new Properties();
            //try {
            //    prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("common.conf"));
            //} catch (IOException e) {
            //    e.printStackTrace();
            //}
            //
            //String str = prop.getProperty(String.valueOf(i));
            // 创建一条文本消息
            TextMessage message = session.createTextMessage("Topic 发送消息" +i);
            System.out.println("发送消息：Topic 发送消息" + i);
            // 通过消息生产者发出消息
            messageProducer.send(message);
        }

    }
}
